from tinyops.library.task import TaskTargetLogger, TaskEnv


def build_export_command(exports: list) -> str:
    export_values = r'\n'.join(['%s=${%s}' % (x, x) for x in exports])
    export_command = (
        f'tinyops_temp_export_file=$(mktemp -t tinyops_temp_export_file.XXXXXXXXXX)\n'
        f'echo -e "{export_values}" > $tinyops_temp_export_file\n'
        f'echo tinyops_temp_export_file=$tinyops_temp_export_file\n'
    )
    return export_command


def get_export_file(outputs: list) -> str:
    prefix = 'tinyops_temp_export_file='
    for block in reversed(outputs):
        for line in reversed(block.splitlines()):
            line = line.strip()
            if line.startswith(prefix):
                export_file = line[len(prefix):]
                return export_file
    return None


def parse_export_values(content: str) -> dict:
    export_values = {}
    for line in content.splitlines(keepends=False):
        if '=' not in line:
            continue
        key, value = line.split('=', 1)
        export_values[key.strip()] = value.strip()
    return export_values


class ExportHelper:
    def __init__(self, env: TaskEnv, logger: TaskTargetLogger, handler: callable):
        self._env = env
        self._log = logger.log
        self._handler = handler
        self._exports = None

    def before_run(self, script: str, exports: list = None):
        self._exports = exports
        if exports:
            exports_names = ','.join(exports)
            self._log(f'## EXPORT {exports_names}', sep='>')
            script += '\n' + build_export_command(exports)
        return script

    def after_run(self, outputs: list) -> bool:
        if not self._exports:
            return True
        export_file = get_export_file(outputs)
        if not export_file:
            self._log('EXPORT failed, not found export file')
            return False
        content = self._handler(export_file)
        if content is None:
            return False
        export_values = parse_export_values(content)
        for k, v in export_values.items():
            self._log(f'EXPORT {k}={v}', sep='*')
        self._env.export(export_values)
        return True
